<template>
  <div class="session-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>会话管理</span>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="会话状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="等待接入" value="WAITING" />
            <el-option label="进行中" value="ACTIVE" />
            <el-option label="已关闭" value="CLOSED" />
          </el-select>
        </el-form-item>
        <el-form-item label="会话类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option label="客服咨询" value="CUSTOMER_SERVICE" />
            <el-option label="教练咨询" value="COACH_CONSULT" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="会话ID" width="80" />
        <el-table-column label="会员信息" width="200">
          <template #default="{ row }">
            <div class="user-cell">
              <el-avatar :src="row.member?.avatar" :size="32" />
              <span>{{ row.member?.nickname || row.member?.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="客服信息" width="200">
          <template #default="{ row }">
            <div v-if="row.staff" class="user-cell">
              <el-avatar :src="row.staff?.avatar" :size="32" />
              <span>{{ row.staff?.nickname || row.staff?.username }}</span>
            </div>
            <span v-else class="text-secondary">未分配</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="会话标题" width="180" />
        <el-table-column label="会话类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.type === 'CUSTOMER_SERVICE' ? '客服咨询' : '教练咨询' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'WAITING'" type="warning">等待</el-tag>
            <el-tag v-else-if="row.status === 'ACTIVE'" type="success">进行中</el-tag>
            <el-tag v-else type="info">已关闭</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="未读消息" width="100">
          <template #default="{ row }">
            <el-badge :value="row.unreadCount + row.staffUnreadCount" />
          </template>
        </el-table-column>
        <el-table-column label="评分" width="120">
          <template #default="{ row }">
            <el-rate v-if="row.rating" :model-value="row.rating" disabled />
            <span v-else class="text-secondary">未评分</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="viewSession(row.id)">
              查看详情
            </el-button>
            <el-button 
              v-if="row.status === 'ACTIVE'" 
              link 
              type="warning" 
              @click="closeSession(row.id)"
            >
              关闭会话
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadData"
        @current-change="loadData"
      />
    </el-card>

    <!-- 会话详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="会话详情" width="800px">
      <el-descriptions v-if="currentSession" :column="2" border>
        <el-descriptions-item label="会话ID">{{ currentSession.id }}</el-descriptions-item>
        <el-descriptions-item label="会话类型">
          {{ currentSession.type === 'CUSTOMER_SERVICE' ? '客服咨询' : '教练咨询' }}
        </el-descriptions-item>
        <el-descriptions-item label="会员">
          {{ currentSession.member?.nickname || currentSession.member?.username }}
        </el-descriptions-item>
        <el-descriptions-item label="客服">
          {{ currentSession.staff?.nickname || currentSession.staff?.username || '未分配' }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="currentSession.status === 'WAITING'" type="warning">等待</el-tag>
          <el-tag v-else-if="currentSession.status === 'ACTIVE'" type="success">进行中</el-tag>
          <el-tag v-else type="info">已关闭</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="评分">
          <el-rate v-if="currentSession.rating" :model-value="currentSession.rating" disabled />
          <span v-else>未评分</span>
        </el-descriptions-item>
        <el-descriptions-item label="评分备注" :span="2">
          {{ currentSession.ratingComment || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDateTime(currentSession.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="关闭时间">
          {{ currentSession.closedAt ? formatDateTime(currentSession.closedAt) : '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSessionList, closeSession as apiCloseSession, type ChatSession } from '@/api/modules/chat'
import { useRouter } from 'vue-router'

const router = useRouter()

const searchForm = ref({
  status: '',
  type: ''
})

const tableData = ref<ChatSession[]>([])
const pagination = ref({
  page: 1,
  pageSize: 20,
  total: 0
})

const showDetailDialog = ref(false)
const currentSession = ref<ChatSession | null>(null)

onMounted(() => {
  loadData()
})

async function loadData() {
  try {
    const { data } = await getSessionList({
      status: searchForm.value.status,
      type: searchForm.value.type,
      page: pagination.value.page,
      pageSize: pagination.value.pageSize
    })
    
    tableData.value = data.list
    pagination.value.total = data.total
  } catch (error: any) {
    ElMessage.error('加载数据失败: ' + error.message)
  }
}

function handleSearch() {
  pagination.value.page = 1
  loadData()
}

function handleReset() {
  searchForm.value = {
    status: '',
    type: ''
  }
  handleSearch()
}

async function viewSession(id: number) {
  try {
    const session = tableData.value.find(s => s.id === id)
    if (session) {
      currentSession.value = session
      showDetailDialog.value = true
    }
  } catch (error: any) {
    ElMessage.error('查看详情失败: ' + error.message)
  }
}

async function closeSession(id: number) {
  try {
    await ElMessageBox.confirm('确定要关闭这个会话吗？', '提示', {
      type: 'warning'
    })
    
    await apiCloseSession(id, {})
    ElMessage.success('会话已关闭')
    loadData()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('关闭失败: ' + error.message)
    }
  }
}

function formatDateTime(time: string): string {
  return new Date(time).toLocaleString('zh-CN')
}
</script>

<style scoped lang="scss">
.session-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 16px;
  }

  .user-cell {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .text-secondary {
    color: #999;
  }

  :deep(.el-pagination) {
    margin-top: 16px;
    justify-content: flex-end;
  }
}
</style>

